package com.qf.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qf.pojo.R;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return -5;
    }

    @Override
    public boolean shouldFilter() {
        //ThreadLocal
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String uri = request.getRequestURI();
        //针对uri进行判断，如果是登录、注册相关资源，不拦截-- 返回false
        //其他的都拦截 -- 返回true
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //从请求中获取用户的登录信息（浏览器的token）--获取浏览器的token(头信息、路径参数)
        //String token = request.getHeader("token");
        String token = request.getParameter("token");

        if (token != null && token.length() != 0){
            //校验（jwt校验逻辑）,校验通过，放心访问；校验失败，阻止访问
        }else{
            try {
                //没携带登录信息，必然要阻止访问
                //zuul阻止过滤器继续向下执行，到此为止
                currentContext.setSendZuulResponse(false);

                //向页面响应一点提示信息
                R r = R.error().putMsg("请先登录");
                ObjectMapper om = new ObjectMapper();
                String json = om.writeValueAsString(r);

                HttpServletResponse response = currentContext.getResponse();
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(json);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //这个放回置没有任何意义，主要考虑后期框架升级使用
        return null;
    }
}
